package com.css.fxfzysx.modules.lifeline.rest;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.css.fxfzysx.modules.lifeline.param.CircleParam;
import com.css.fxfzysx.modules.lifeline.rest.bo.AreaBo;
import com.css.fxfzysx.modules.lifeline.rest.bo.ChinaGridBo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Properties;

@Slf4j
@Component
public class JcsjRestManager {

    @Autowired
    private RestTemplate restTemplate;

    private static final String GEOGRAPHIC_LOCATION_BY_RANGE = "chinaGrid/geomByRange";

    //面积
    private static final String AREA_BY_NAME = "datacenter/sysDataVersion/getByCountName";

    //全国所有的县
    private static final String ALL_COUNTY_NAME = "datacenter/sysDataVersion/getAllZoning";
    private static final String COMPLETE = "buildingGrid/getComplete";

    /**
     * 获取基础请求路径
     *
     * @return
     */
    private static String getBaseUrl(String apiUrl) throws Exception {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String jcsjRestUrl = configGroup.getProperty("jcsjRestUrl");
        if (StringUtils.isBlank(jcsjRestUrl)) {
            throw new Exception("配置文件未发现基础数据系统接口URL");
        }
        if (!StringUtils.endsWith(jcsjRestUrl, "/")) {
            jcsjRestUrl += "/";
        }
        return jcsjRestUrl + apiUrl;
    }

    private static String getBaseUrl1(String apiUrl) throws Exception {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String jcsjRestUrl = configGroup.getProperty("fxqhRestUrl");
        if (StringUtils.isBlank(jcsjRestUrl)) {
            throw new Exception("配置文件未发现基础数据系统接口URL");
        }
        if (!StringUtils.endsWith(jcsjRestUrl, "/")) {
            jcsjRestUrl += "/";
        }
        return jcsjRestUrl + apiUrl;
    }

    private static <T> String buildGetMethodParam(T param) {
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(param, SerializerFeature.WriteDateUseDateFormat));
        StringBuilder str = new StringBuilder("?");
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            str.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }

        String s = str.toString();
        if (s.endsWith("?")) {
            return StringUtils.removeEnd(s, "?");
        } else {
            return StringUtils.removeEnd(s, "&");
        }
    }

    /**
     * 构建一个基础的请求头
     *
     * @return
     */
    private static HttpHeaders buildBaseHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "dzzhfxpgyqhxt");
        headers.setContentType(MediaType.APPLICATION_JSON);
        return headers;
    }

    public String getGeographicLocationByRange(CircleParam.range range){
        long startTime = System.currentTimeMillis();
        HttpEntity<CircleParam.range> entity = new HttpEntity<>(range, buildBaseHeaders());
        String url = null;
        try {
            url = getBaseUrl(GEOGRAPHIC_LOCATION_BY_RANGE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //设置超时时间
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(0);
        clientHttpRequestFactory.setReadTimeout(0);

        restTemplate.setRequestFactory(clientHttpRequestFactory);
        try {
            ChinaGridBo body = restTemplate.exchange(url, HttpMethod.POST, entity, ChinaGridBo.class).getBody();
            long endTime = System.currentTimeMillis();
            log.info("远程调用用时:{}", (endTime - startTime) + "ms");
            return body.getData();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    public AreaBo getCountyName() throws Exception {
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl(ALL_COUNTY_NAME);
        //设置超时时间
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(0);
        clientHttpRequestFactory.setReadTimeout(0);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, AreaBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    public AreaBo getAreaByCountName(String countName) throws Exception {
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        JSONObject param = new JSONObject();
        param.put("countName", countName);
        String url = getBaseUrl(AREA_BY_NAME) + buildGetMethodParam(param);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, AreaBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    public AreaBo getComplete() throws Exception {
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl1(COMPLETE);
        //设置超时时间
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(0);
        clientHttpRequestFactory.setReadTimeout(0);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, AreaBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }
}
